package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.pojo.Setmeal;
import com.itheima.service.OrderService;
import com.itheima.service.SetmealService;
import com.itheima.utils.SMSUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Arrays;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private OrderService orderService;
    @Reference
    private SetmealService setmealService;
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){
//        获取到用户输入的验证码
        String validateCode = (String) map.get("validateCode");
//        从Redis取出生成的验证码
        String telephone = (String) map.get("telephone");
        String orderDate = (String) map.get("orderDate");
        String setmealId = (String)map.get("setmealId");
        Setmeal setmeal = setmealService.findSetmealById(Integer.parseInt(setmealId));
        String setmealName = setmeal.getName();
        String[] telephones = {"+86"+telephone};
        String[] params = {setmealName,orderDate};
        map.put("telephones",telephones);
        map.put("params", params);
        System.out.println(Arrays.toString(params));
        String redisCode = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);

//        对比如果成功调用服务 如果失败返回结果给页面
        if (validateCode!=null&&redisCode!=null&&validateCode.equals(redisCode)){
//            设置预约类型，分为微信预约，电话预约
            Result result =null;
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            try {
                 result = orderService.order(map);

            } catch (Exception e) {
                e.printStackTrace();
                return result;

            }
            return result;

        }else {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }
    @RequestMapping("/findById")
    public Result findById(Integer id ){
        try {
            Map map = orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }

}
